package modele;
import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.Constructor;

/**
 * create a filter which select files who finished by .class , implemented by plugin and have a default constructor
 * @author morhib & moyart
 *
 */
public class PluginFilter implements FilenameFilter{

	@Override
	public boolean accept(File dir, String s) {

		if(!s.endsWith(".class"))
			return false;

		Class<?> theClass=getClass(dir,s);
		if(theClass==null)
			return false;
		

		return inheritFromPlugin(theClass) && classInPluginPackages(theClass) && classTruc(theClass);
	}

	private Class<?> getClass(File dir, String s) {
		String classname= s.replaceFirst("\\.class$", "");
		System.out.println(classname);
		try{
			return Class.forName("plugins."+classname);
		}
		catch(ClassNotFoundException e){
			return null;
		}
	}

	private boolean classTruc(Class<?> theClass) {
		for(Constructor<?> cons : theClass.getConstructors())
			if(cons.getParameterTypes().length==0)
				return true;

		return false;
	}

	private boolean classInPluginPackages(Class<?> theClass) {
		return theClass.getPackage().getName().equals("plugins");
	}

	private boolean inheritFromPlugin(Class<?> theClass) {
		return Plugin.class.isAssignableFrom(theClass);
	}


}
